﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;

namespace DataFlock.CRM.Engine.Helpers
{
    internal static class ConfiguratationHelper
    {
        internal const string ENGINE_CONFIG = "ENGINE";
        internal const string CRM_CONFIG = "CRM";

        private static string _configurationFilePath = string.Empty;

        private static string ConfigurationFilePath
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_configurationFilePath))
                {
                    _configurationFilePath = Path.Combine(Directory.GetCurrentDirectory(), "CRMEngine.ini");
                }
                return _configurationFilePath;
            }
        }

        [DllImport("KERNEL32.DLL", EntryPoint = "WritePrivateProfileStringW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        private static extern int WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFilename);

        [DllImport("KERNEL32.DLL", EntryPoint = "GetPrivateProfileStringW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, string lpReturnString, int nSize, string lpFilename);

        public static string GetConfiguration(string key)
        {
            return GetConfiguration(ENGINE_CONFIG, key);
        }

        public static string GetConfiguration(string category, string key)
        {
            string returnString = new string(' ', 1024);
            GetPrivateProfileString(category, key, string.Empty, returnString, 1024, ConfigurationFilePath);
            return returnString.Split('\0')[0];
        }

        public static void SetConfiguration(string category, string key, string value)
        {
            WritePrivateProfileString(category, key, value, ConfigurationFilePath);
        }

        public static void SetConfiguration(string key, string value)
        {
            SetConfiguration(ENGINE_CONFIG, key, value);
        }
    }
}
